using System.Collections;
using UnityEngine;

public class WeaponManager : MonoBehaviour
{
    [Header("魔法飞弹设置")]
    [SerializeField] private GameObject magicMissilePrefab; // 飞弹预制体
    [SerializeField] private float missileCooldown = 2.0f; // GDD里的基础冷却时间

    private float missileTimer; // 冷却计时器

    void Start()
    {
        missileTimer = missileCooldown; // 游戏开始时就可以发射
    }

    void Update()
    {
        // 魔法飞弹的冷却计时
        missileTimer += Time.deltaTime;

        if (missileTimer >= missileCooldown)
        {
            missileTimer = 0f; // 重置计时器
            FireMagicMissile();
        }
    }

    private void FireMagicMissile()
    {
        // 1. 寻找最近的敌人
        Transform nearestEnemy = FindNearestEnemy();

        // 2. 如果找到了敌人
        if (nearestEnemy != null)
        {
            // 3. 在玩家位置创建飞弹实例
            GameObject missile = Instantiate(magicMissilePrefab, transform.position, Quaternion.identity);

            // 4. 告诉飞弹它的目标是谁
            missile.GetComponent<MagicMissileController>().SetTarget(nearestEnemy);
        }
    }

    private Transform FindNearestEnemy()
    {
        // 找到场景中所有带 "Enemy" 标签的对象
        GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
        
        Transform nearest = null;
        float minDistance = Mathf.Infinity;
        Vector3 currentPosition = transform.position;

        foreach (GameObject enemy in enemies)
        {
            float distance = Vector3.Distance(enemy.transform.position, currentPosition);
            if (distance < minDistance)
            {
                minDistance = distance;
                nearest = enemy.transform;
            }
        }
        return nearest;
    }
}